<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
    <title>工时填报</title>
    <link rel="stylesheet" href="/plugins/layui/css/layui.css" media="all">
    <link rel="stylesheet" type="text/css" href="/build/css/css/font-awesome.min.css">
    <link rel="stylesheet" type="text/css" href="/css/easyui.css">
    <link rel="stylesheet" type="text/css" href="/css/my-style.css">
    <style>        /* 防止下拉框的下拉列表被隐藏---必须设置--- */
    .layui-table-cell {
        overflow: visible !important;
    }

    /* 设置下拉框的高度与表格单元相同 */
    .layui-input, .layui-select, .layui-textarea {
        height: 30px !important;
    }

    </style>
</head>

<body>
<div class="kit-doc">
    <!--表格搜索框组-->
    <div class="layui-form-item layui-formgroup layui-tab-card">
        <div class="layui-inline">
            <form class="layui-form " action="">
                <input type="hidden" id="monday">
                <input type="hidden" id="sunday">
                <label class="layui-form-label">项目：</label>
                <div class="layui-input-inline">
                    <select name="project" id="searchProject" lay-verify="required" lay-search="">
                        <option value=""></option>
                        <option value="" th:each="project : ${projectList}" th:value="${project.getId()}" th:text="${project.getProjectName()}"></option>
                    </select>
                </div>
            </form>
        </div>
        <!-- 时间 -->
        <div class="layui-inline">
            <label class="layui-form-label">日期：</label>
            <div class="layui-input-inline">
                <input class="layui-input" id="test6" placeholder=" 时间段 " type="text" readonly="readonly" disabled="disabled">
            </div>
        </div>

        <!-- 按钮 -->
        <button class="layui-btn layui-btn-sm" id="searchBtn">搜索</button>
        <button class="layui-btn layui-btn-primary layui-btn-sm" id="preWeekBtn">
            <i class="fa fa-reply margin-r3"></i>上一周
        </button>
        <button class="layui-btn layui-btn-primary layui-btn-sm" id="thisWeekBtn">
            <i class="fa fa-search margin-r3"></i>本周
        </button>
        <button class="layui-btn layui-btn-primary layui-btn-sm" id="nextWeekBtn">
            <i class="fa fa-share margin-r3"></i>下一周
        </button>
    </div>

    <div class="layui-card layui-card-body gs-box">
        <div id="tb" style="height:auto">
            <a href="javascript:void(0)" class="easyui-linkbutton l-btn-text" id="addBtn">
                <i class="fa fa-plus"></i> 录入
            </a>
            <a href="javascript:void(0)" class="easyui-linkbutton l-btn-text" id="saveBtn">
                <i class="fa fa-check"></i> 保存
            </a>
<!--            <a href="javascript:void(0)" class="easyui-linkbutton l-btn-text" id="excelsaveBtn">-->
<!--                <i class="fa fa-check"></i> 提交-->
<!--            </a>-->
        </div>
        <table class="layui-table xuhao-table" id="table-context" lay-filter="test">
            <script type="text/html" id="barDemo">
                <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
            </script>
        </table>
    </div>
</div>

<script type="text/html" id="projectTpl">
    <select name="project" id="project_{{d.id}}" lay-filter="projectSelect" lay-verify="required" lay-search="" >
<!--        <option value=""></option>-->
        <option value="" th:each="project : ${projectList}" th:value="${project.getId()}" th:text="${project.getProjectName()}"></option>
    </select>
</script>



<!--<script type="text/html" id="typeTpl">-->
<!--    <select name="project" id="type_{{d.id}}" lay-filter="typeSelect" lay-verify="required" lay-search="">-->
<!--        <option value=""></option>-->
<!--        <option value="" th:each="type : ${typeList}" th:value="${type.getId()}" th:text="${type.getTypeName()}"></option>-->
<!--    </select>-->
<!--</script>-->

<script src="/js/jquery.min.js"></script>
<script src="/plugins/layui/layui.js"></script>
<script src="/js/workhour.js"></script>
<script>
    Array.prototype.remove = function (from, to) {
        var rest = this.slice((to || from) + 1 || this.length);
        this.length = from < 0 ? this.length + from : from;
        return this.push.apply(this, rest);
    };
</script>
<script>
    Date.prototype.format = function (fmt) {
        var o = {
            "M+": this.getMonth() + 1,                 //月份
            "d+": this.getDate(),                    //日
            "h+": this.getHours(),                   //小时
            "m+": this.getMinutes(),                 //分
            "s+": this.getSeconds(),                 //秒
            "q+": Math.floor((this.getMonth() + 3) / 3), //季度
            "S": this.getMilliseconds()             //毫秒
        };
        if (/(y+)/.test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
        }
        for (var k in o) {
            if (new RegExp("(" + k + ")").test(fmt)) {
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
            }
        }
        return fmt;
    }
    /*
     * 重写时间的toJSON方法，因为在调用JSON.stringify的时候，时间转换就调用的toJSON，这样会导致少8个小时，所以重写它的toJSON方法
     */
    Date.prototype.toJSON = function () {
        return this.format("yyyy-MM-dd hh:mm:ss"); // util.formatDate是自定义的个时间格式化函数
    };

    var now = new Date();

    // 获取周一和周末
    var start = getTime(0, now);
    $("#monday").val(start);
    var end = getTime(-6, now);
    $("#end").val(end);

    layui.use(['table', 'jquery', 'form','upload'], function () {
        // 保存上次查询的数据
        var table = layui.table;
        var $ = layui.jquery
            ,upload = layui.upload;
        var form = layui.form;
        var projectTable = table.render({
            elem: '#table-context'
            , url: '/workhours/view/me'
            , height: 'full-200'
            , page: true
            , limit: 10
            , limits: [10, 20, 30]
            ,even: true
            , request: {
                pageName: 'page' //页码的参数名称，默认：page
                , limitName: 'size' //每页数据量的参数名，默认：limit
            }
            , cols: [
                [

                    {
                        field: 'projectId',
                        title: '项目名称',
                        templet: '#projectTpl',
                        width: '18%',
                        align: 'center',
                    }, //width 支持：数字、百分比和不填写。你还可以通过 minWidth 参数局部定义当前单元格的最小宽度，layui 2.2.1 新增
                    // {
                    //     field: 'projectTypeId',
                    //     title: '项目类型',
                    //     templet: '#typeTpl',
                    //     width: '10%',
                    //     align: 'center'
                    // },
                    {
                        field: 'remark',
                        title: '任务信息',
                        minWidth: 180,
                        edit: 'text',
                        align: 'center'
                    },
                    {
                        field: 'workDate',
                        title: '工作日期',
                        width: '12%',
                        align: 'center',
                        templet: function (d) {
                            return '<input type="text" name="workDate" verify lay-verify="verify" value="' + (d.workDate || '') + '" placeholder="请选择时间" readonly="readonly" class="layui-input layui-input-date" style="text-align: center"/>';
                        }
                    },
                    {
                        title: '工时',
                        field: 'workHours',
                        edit: 'text',
                        align: 'center',
                        width: '10%'
                    },
                    {
                        title: '审核状态',
                        // field: 'reviewFlag',
                        align: 'center',
                        width: '10%',
                        templet: function (data) {
                            // console.log("渲染时")
                            // console.log(data)
                            if(data!=null){
                                var html = "";
                                if(data.reviewFlag === '0'){
                                    html += '<a class=" layui-btn layui-btn-sm  layui-btn-radius layui-btn-primary" lay-event="again">未审核</a>'
                                }
                                else if(data.reviewFlag === '1'){
                                    html += '<a class=" layui-btn layui-btn-sm  layui-btn-radius layui-btn-normal" lay-event="again">审核通过</a>'
                                }
                                else if(data.reviewFlag === '2'){
                                    html += '<a class=" layui-btn layui-btn-sm  layui-btn-radius layui-btn-danger" lay-event="again">审核失败</a>'
                                }
                                // console.log("渲染后")
                                // console.log(data)
                                return html;
                            }

                        }
                    },
                    {
                        title: '操作',
                        fixed: 'right',
                        align: 'center',
                        width: '8%',
                        toolbar: '#barDemo'
                    }
                ]
            ]
            , done: function (res, curr, count) {

                var that = this.elem.next();
                res.data.forEach(function (item, index) {
                    if (item.reviewFlag == '1') {
                        // var tr = that.find(".layui-table-box tbody tr[data-index='" + index + "']").css("background-color", "#7FFFD4");
                        var tr = that.find(".layui-table-box tbody tr[data-index='" + index + "']")
                        // 禁用单元格编辑
                        tr.find('td').data('edit', false)
                        // 禁用下拉栏选择
                        tr.find('td').find('select').attr('disabled', 'disabled')
                        // 禁用时间选择器选择
                        tr.find('td').find('input').attr('disabled', 'disabled')
                    }
                });
                $("table tr").find("td:eq(2)").css("overflow","hidden")
                ///让表格中的select默认选中
                for (var i = 0; i < res.data.length; i++) {

                    $("#project_" + res.data[i].id).val(res.data[i].projectId);//atype是select的id
                    $("#type_" + res.data[i].id).val(res.data[i].projectTypeId);//atype是select的id
                }
                form.render('select');

                //日期控件
                $(".layui-input-date").each(function (i) {
                    layui.laydate.render({
                        elem: this,
                        format: "yyyy-MM-dd",
                        done: function (value, date) {
                            if (res && res.data[i]) {
                                $.extend(res.data[i], {'workDate': value})
                            }
                        }
                    });
                });

            }
        });

        // 保存是否被编辑
        var isEdit = false;

        /**
         * 下拉选择项目名称
         */
        form.on('select(projectSelect)', function (obj) {
            var index = $(obj.elem).parent().parent().parent().index();
            var tableData = table.cache["table-context"];
            tableData[index].projectId = obj.value;
            isEdit = true;
        });

        form.on('select(typeSelect)', function (obj) {
            var index = $(obj.elem).parent().parent().parent().index();
            var tableData = table.cache["table-context"];
            tableData[index].projectTypeId = obj.value;
            isEdit = true;
        });

        //监听行工具事件
        table.on('tool(test)', function (obj) { //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
            var data = obj.data //获得当前行数据
                , layEvent = obj.event; //获得 lay-event 对应的值
            if (layEvent === 'del') {
                layer.confirm('确定删除当前行？', function (index) {
                    // console.log(obj.data)
                    obj.del(); //删除对应行（tr）的DOM结构,并更新缓存
                    layer.close(index);
                    if (!isEmpty(data.id)&&parseInt(data.id)>11) {
                        //向服务端发送删除指令
                        layui.$.ajax({
                            type: 'DELETE',
                            url: "/workhours/del/" + data.id,
                            success: function (res) {
                                layer.closeAll();
                                if (res.code == 0) {
                                    layer.msg("删除成功");
                                    refresh();
                                    // window.location.reload();
                                } else {
                                    layer.msg("修改失败" + res.msg);
                                }
                            }
                        });
                    }
                    else {
                        var temp =[];
                        //过滤掉内容为[]的对象
                        table.cache["table-context"].forEach(item => {
                            if (Object.keys(item).length > 0){
                                temp.push(item)
                            }
                        })
                        table.cache["table-context"] = temp;
                        projectTable.reload({
                            url: "",
                            data: temp
                        });
                    }
                });
            }else if(layEvent === 'again') {
                layer.confirm('确定重新提交审核吗？', function (index) {
                    layer.close(index);
                    if(data.reviewFlag === '1'){
                        layer.confirm('通过审核后不可重复提交！', function (index) {
                            layer.close(index);
                        });
                    }else{
                        data.reviewFlag = '0'
                        layui.$.ajax({
                            type: 'PUT',
                            url: "/workhours/update/"+ data.id,
                            contentType: "application/json",
                            dataType: 'json',
                            data: JSON.stringify(data),
                            success: function (res) {
                                layer.closeAll();
                                if (res.code == 0) {
                                    refresh();
                                    layer.msg("操作成功");
                                } else {
                                    layer.msg("操作失败" + data.msg);
                                }
                            }
                        });
                    }

                });}
        });

        //监听单元格编辑
        table.on('edit(test)', function (obj) {
            isEdit = true;
            // 单元格修改后，将其审核状态改为  未审核
            obj.update({
                reviewFlag: "0"
            })
        });
        var num=0;
        $(function () {
            num=0;
        })
        // 添加数据
        $("#addBtn").click(function () {
            num++;
            isEdit = true;
            var newRow = {
                id: num,
                projectId: null,
                projectTypeId: null,
                userId: null,
                workDate: null,
                workHours: 7.5,
                delFlag: null,
                remark: null
            };

            var oldData = table.cache["table-context"];
            oldData.push(newRow);
            projectTable.reload({
                url: "",
                data: oldData
            });
        });

        /**
         * 搜索
         */
        $("#searchBtn").click(function () {
            refresh();
        });

        function refresh(){
            var searchProjectContext = $("#searchProject").val();
            var start = $("#test6").val().split(' - ')[0];
            var end = $("#test6").val().split(' - ')[1];
            projectTable.reload({
                where: { //设定异步数据接口的额外参数，任意设
                    projectId: searchProjectContext,
                    startDate: start,
                    endDate: end
                }
            });
        }

        // 保存操作
        $("#saveBtn").click(function () {
            if (isEdit) {
                // 获取表格数据
                var tableData = table.cache["table-context"];
                // console.log(tableData);
                // var monDate = new Date($("#monday").val());
                for (var i = 0; i < tableData.length; i++) {
                    var rowData = tableData[i];
                    //去掉新增的行的ID
                    if(tableData[i].id<=11){
                        tableData[i].id=null;
                    }
                    // 一周是否只填写了一天
                    // var isOne = false;
                    // if (!isEmpty(rowData.mon)) {
                    //     // rowData.workHours = rowData.mon;
                    //     // rowData.workDate = monDate;
                    //     isOne = true;
                    // }
                    // if (!isEmpty(rowData.tues)) {
                    //     // rowData.workHours = rowData.tues;
                    //     // rowData.workDate = addDate(monDate, 1);
                    //     isOne = !isOne;
                    // }
                    // if (!isEmpty(rowData.wed)) {
                    //     // rowData.workHours = rowData.wed;
                    //     // rowData.workDate = addDate(monDate, 2);
                    //     isOne = !isOne;
                    // }
                    // if (!isEmpty(rowData.thur)) {
                    //     // rowData.workHours = rowData.thur;
                    //     // rowData.workDate = addDate(monDate, 3);
                    //     isOne = !isOne;
                    // }
                    // if (!isEmpty(rowData.fri)) {
                    //     // rowData.workHours = rowData.fri;
                    //     // rowData.workDate = addDate(monDate, 4);
                    //     isOne = !isOne;
                    // }
                    // if (!isEmpty(rowData.stat)) {
                    //     // rowData.workHours = rowData.stat;
                    //     // rowData.workDate = addDate(monDate, 5);
                    //     isOne = !isOne;
                    // }
                    // if (!isEmpty(rowData.sun)) {
                    //     // rowData.workHours = rowData.sun;
                    //     // rowData.workDate = addDate(monDate, 6);
                    //     isOne = !isOne;
                    // }

                    // if (isEmpty(rowData.projectTypeId)) {
                    //     layer.msg("第" + (i + 1) + "行,请选择项目类型！");
                    //     return;
                    // }
                    if (isEmpty(rowData.projectId)) {
                        layer.msg("第" + (i + 1) + "行,请选择项目名称！");
                        return;
                    }
                    if (isEmpty(rowData.remark)) {
                        layer.msg("第" + (i + 1) + "行,工作任务不能为空！");
                        return;
                    }
                    if (isEmpty(rowData.workDate)) {
                        layer.msg("第" + (i + 1) + "行,时间不能为空！");
                        return;
                    }
                    // if (!isOne || isNaN(parseFloat(rowData.workHours))) {
                    if (isNaN(parseFloat(rowData.workHours))) {
                        layer.msg("第" + (i + 1) + "行,工时填写有误，请检查后再保存");
                        return;
                    }
                    if (isNaN(parseFloat(rowData.workHours))) {
                        layer.msg("第" + (i + 1) + "行,工作时间填写有误！，请检查后再保存");
                        return;
                    }
                }
                // console.log(JSON.stringify(tableData));

                //批量增加修改
                $.ajax({
                    type: 'POST',
                    url: "/workhours/add",
                    contentType: "application/json",
                    dataType: 'json',
                    data: JSON.stringify(tableData),
                    success: function (res) {
                        layer.closeAll();
                        if (res.code == 0) {
                            projectTable.reload({
                                url: '/workhours/view/me',
                                page: {
                                    curr: 1 //重新从第 1 页开始
                                }
                            })
                            layer.msg("保存成功！");
                        } else {
                            layer.msg("保存失败！" + res.msg);
                        }
                    }
                })
            } else {
                layer.msg("请编辑行！");
            }
        });

        //excel导入
        // var uploadInst = upload.render({
        //     elem:'#excelsavebtn'
        //     ,url:'/uploadexcel'
        //     ,before:function (obj) {
        //         obj.preview(function (index,file,result) {
        //             $('#demo1').attr('src',result);
        //         });
        //     }
        //     ,done:function (res) {
        //         if(res.code>0){
        //             return layer.msg("上传失败");
        //         }
        //
        //     }
        //     ,error:function () {
        //         var demoText = $('#demoText');
        //         demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
        //         demoText.find('.demo-reload').on('click', function () {
        //             uploadInst.upload();
        //         });
        //     }
        // });


        // 上一周
        $("#preWeekBtn").click(function () {
            var monDate = $("#monday").val();
            var preMon = dateToStr(addDate(monDate, -7));
            var preSun = dateToStr(addDate(monDate, -1));
            $("#monday").val(preMon);
            $("#sunday").val(preSun);
            $("#test6").val(preMon + ' - ' + preSun);
            projectTable.reload({
                where: { //设定异步数据接口的额外参数，任意设
                    projectId: $("#searchProject").val(),
                    startDate: preMon,
                    endDate: preSun
                }
                , page: {
                    curr: 1 //重新从第 1 页开始
                }
            })
        });

        // 下一周
        $("#nextWeekBtn").click(function () {
            var monDate = $("#monday").val();
            var nextMon = dateToStr(addDate(monDate, 7));
            var nextSun = dateToStr(addDate(monDate, 13));
            $("#monday").val(nextMon);
            $("#sunday").val(nextSun);
            $("#test6").val(nextMon + ' - ' + nextSun);
            projectTable.reload({
                where: { //设定异步数据接口的额外参数，任意设
                    projectId: $("#searchProject").val(),
                    startDate: nextMon,
                    endDate: nextSun
                }
                , page: {
                    curr: 1 //重新从第 1 页开始
                }
            })
        });

        // 本周一周
        $("#thisWeekBtn").click(function () {
            var now = new Date();
            // 获取周一和周末
            var start = getTime(0, now);
            var end = getTime(-6, now);

            $("#monday").val(start);
            $("#sunday").val(end);
            $("#test6").val(start + ' - ' + end);
            projectTable.reload({
                where: { //设定异步数据接口的额外参数，任意设
                    projectId: $("#searchProject").val(),
                    startDate: start,
                    endDate: end
                }
                , page: {
                    curr: 1 //重新从第 1 页开始
                }
            })
        });
    });


</script>
</body>
</html>